/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  themes_default
 */

window.onunload = function(){
	if($("#refreshOpener").val() == "true")
	{
		window.opener.refreshRightCol($("#fileName").text(), $("#fileSize").text());		
	}
};

$(document).ready(function()
{	
	var origWidth = $("#image").width();
	var origHeight = $("#image").height();
	var ratio = origWidth/origHeight;
	
	var imgWidth = origWidth;
	var imgHeight = origHeight;
	var mLeft;
	var startPercent;
	
	var percent;
	
	$("#sliderContainer").draggable({
		handle: "#sliderTitle",
		cursor: 'move',
		appendTo: "#page" 
	});
	
	$("#picContainer").draggable({ 
		handle: '#containerTitle',
		cursor: 'move',
		appendTo: "#page" 
	});
	
	$("#container").resizable({
		start: function(event, ui){
			$("#refreshOpener").val("false");
			origImgWidth = $("#image").width();
			origImgHeight = $("#image").height();
			mLeft = parseInt($("#image").css("margin-left").replace(/px/, ""));
			mTop = parseInt($("#image").css("margin-top").replace(/px/, ""));
			$("#container").unbind("mousedown mousemove");
		},
		resize: function(event, ui){			
			if($(this).width() >= origImgWidth-Math.abs(mLeft))
			{
				limitw = origImgWidth-$(this).width();
				if(limitw >= 0)
				{
					$("#image").css("margin-left", -limitw+"px");
				}
				else
				{
					$("#image").css("margin-left", "0px");
					$(this).width(origImgWidth+"px");					
				}				
			}		
			
			if($(this).height() >= origImgHeight-Math.abs(mTop))
			{
				limith = origImgHeight-$(this).height();
				if(limith >= 0)
				{
					$("#image").css("margin-top", -limith+"px");
				}
				else
				{
					$("#image").css("margin-top", "0px");
					$(this).height(origImgHeight+"px");					
				}
			}
			$("#picContainer").width($(this).width()+1);
			$("#selectWidth").text($(this).width());		
			$("#containerWidth").val($(this).width());		
			$("#selectHeight").text($(this).height());		
			$("#containerHeight").val($(this).height());
			$("#formatSizes option[value='']").attr('selected', 'selected');
			
			if($("#containerWidth").val() == origWidth && $("#containerHeight").val() == origHeight)
			{		
				$("#saveButton").attr("disabled", "disabled");		
			}
			else
			{
				$("#saveButton").removeAttr("disabled");
			}
		},
		stop: function(event, ui)
		{
			getMinPercentage(origWidth, origHeight);
			$("#formatSizes option[value='']").attr('selected', 'selected');
		}
	});
	
	$("#slider").slider({
		orientation: "vertical",
		range: "min",
		min: 100,
		max: 100,
		value: 100,
		start: function(event, ui){
			$("#refreshOpener").val("false");
			CD = parseInt($("#container").width()/2);
			DE = parseInt($("#container").height()/2);
			mLeft = parseInt($("#image").css("margin-left").replace(/px/, ""));
			mTop = parseInt($("#image").css("margin-top").replace(/px/, ""));
			origImgWidth = $("#image").width();
			origImgHeight = $("#image").height();
			startPercent = ui.value;
			diffPercent = $(this).slider("option", "max")-$(this).slider("option", "min");
		},
		slide: function(event, ui) {
			percentage = ((100/startPercent)*ui.value)/100;
			imgPercentage = ui.value/100;
			$("#amount").text(ui.value);
						
			imgWidth = Math.round(origWidth*imgPercentage);
			imgHeight = Math.round(origHeight*imgPercentage);
						
			if(percentage != 0)
			{
				BC = -(-mLeft * percentage)+(origImgWidth-imgWidth)/(origImgWidth/CD);
				EF = -(-mTop * percentage)+(origImgHeight-imgHeight)/(origImgHeight/DE);				
			}
						
			if(BC >= 0)	{ BC = 0; }
			if(EF >= 0)	{ EF = 0; }
			
			if(Math.abs(EF)+DE >= imgHeight/2 && imgHeight-Math.abs(EF) <= (DE*2))
			{
				EF = EF-((imgHeight-(DE*2))-Math.abs(EF));
			}
			
			if(Math.abs(BC)+CD >= imgWidth/2 && imgWidth-Math.abs(BC) <= (CD*2))
			{
				BC = BC-((imgWidth-(CD*2))-Math.abs(BC));
			}

			if(imgWidth+BC >= CD*2 && imgHeight+EF >= DE*2 || imgHeight >= DE*2 && imgWidth >= CD*2)
			{
				$("#image").width(imgWidth).height(imgHeight).css({marginLeft: BC+"px", marginTop: EF+"px"});
				$("#dimWidth").text(imgWidth);				
				$("#dimHeight").text(imgHeight);				
			}
		}
	});	
	
	$("#saveButton").click(function(event){
		text = $.ajax({
			type: "POST",
			url: "?module=medias&action=resizePicture",
			data: ({
				docId:	$("#docId").val(),
				docLang:$("#docLang").val(),
				contW:	$("#container").width(),
				contH:	$("#container").height(),
				picW:	$("#image").width(),
				picH:	$("#image").height(),
				offsetX:Math.abs($("#image").css("margin-left").replace(/px/, "")),
				offsetY:Math.abs($("#image").css("margin-top").replace(/px/, ""))
			}),
			async: false
		}).responseText;
		
		if(text == "50")
		{
			if(confirm("L'image existe déjà dans cette taille, ecraser l'image ?"))
			{
				text = $.ajax({
				type: "POST",
				url: "?module=medias&action=resizePicture",
				data: ({
					docId:	$("#docId").val(),
					docLang:$("#docLang").val(),
					contW:	$("#container").width(),
					contH:	$("#container").height(),
					picW:	$("#image").width(),
					picH:	$("#image").height(),
					offsetX:Math.abs($("#image").css("margin-left").replace(/px/, "")),
					offsetY:Math.abs($("#image").css("margin-top").replace(/px/, "")),
					force: 1
				}),
				async: false
			}).responseText;
			}
		}
		
		if(text == "1")
		{
			infoMessage("Image enregistrée !");
			// used for media selection in wysiwyg
			$("#fileName").text($("#origFileName").text() + "_" + $("#container").width() + "_" + $("#container").height() + "." + $("#origExtension").text());
			$("#fileSize").text($("#container").width() + " x " + $("#container").height());
			$("#refreshOpener").val("true");
		}
	});
	
	$("#formatSizes").change(function(event){
		if($(this).val() != "")
		{
			sizes = $(this).val().split("x");
			width = sizes[0];
			height = sizes[1];
			
			$("#containerWidth").val(width);
			$("#containerHeight").val(height);
			resize(height, width);
			$("#refreshOpener").val("false");
		}
	});
	
	if(origWidth >= origHeight && origWidth > $(document).width())
	{
		$("#image").width($(document).width()-75);
		$("#image").height($("#image").width()/ratio);
		$("#slider").slider("option", "value", Math.round(($("#image").width()/origWidth)*100));
		$("#slider").slider("option", "min", Math.round(($("#image").width()/origWidth)*100));
		$("#amount").text(Math.round(($("#image").width()/origWidth)*100));
	}
	
	if($("#image").height() > $(document).height())
	{
		$("#image").height($(document).height()-100);
		$("#image").width($("#image").height()*ratio);
		$("#slider").slider("option", "value", Math.round(($("#image").height()/origHeight)*100));
		$("#slider").slider("option", "min", Math.round(($("#image").height()/origHeight)*100));
		$("#amount").text(Math.round(($("#image").height()/origHeight)*100));
	}
	
	$("#picContainer").width($("#image").width()+1);
	$("#container").width($("#image").width());
	$("#container").height($("#image").height());
	$("#dimWidth").text($("#image").width());			
	$("#dimHeight").text($("#image").height());			
	$("#selectWidth").text($("#image").width());			
	$("#selectHeight").text($("#image").height());		
	
	$("#sizeButton").click(function(){
		if($("#containerHeight").val() != "" && $("#containerWidth").val() != "")
		{	
			if($("#containerHeight").val() > origHeight || $("#containerWidth").val() > origWidth)
			{
				alert("Le cadre est plus grand que l'image originale");
			}
			else if ($("#containerHeight").val() == origHeight && $("#containerWidth").val() == origWidth)
			{
				alert("Le cadre est égal à la taille de l'image originale");
			}
			else
			{
				destWidth = $("#containerWidth").val();
				destHeight = $("#containerHeight").val();	
				resize(destHeight, destWidth);
				$("#refreshOpener").val("false");				
			}
		}
	})
	
	$("#exitButton").click(function(){
		if($("#refreshOpener").val() == "false")
		{
			if(confirm("Vous n'avez pas enregistré les modifications, voulez vous quitter l'édition de l'image ?") == true)
			{
				window.close();				
			}
		}
		else
		{
			window.close();
		}
	});
	
	function resize(destHeight, destWidth)
	{
		if($("#containerHeight").val() > origHeight)
		{
			destHeight = origHeight;
			destWidth = origHeight*ratio;
		}
		if($("#containerWidth").val() > origWidth)
		{
			destWidth = origWidth;
			destHeight = origWidth/ratio;
		}
	
		$("#container").css({width:destWidth+"px", height:destHeight+"px"});
		getMinPercentage(origWidth, origHeight);
		$("#selectWidth").text(destWidth);	
		$("#containerWidth").val(destWidth);
		$("#selectHeight").text(destHeight);				
		$("#containerHeight").val(destHeight);
		$("#picContainer").css({width:parseInt(destWidth)+1+"px"});
		
		if($("#containerWidth").val() == origWidth && $("#containerHeight").val() == origHeight)
		{
			$("#saveButton").attr("disabled", "disabled");		
		}
		else
		{
			$("#saveButton").removeAttr("disabled");
		}		
	}

	var origPosX = null;
	var origPosY = null;
	var imgX = null;
	var imgY = null;
	
	$(this).mousemove(function(e){	
		if(origPosX > 0)
		{			
			var destX = parseInt(imgX) + (e.pageX - origPosX);
			var destY = parseInt(imgY) + (e.pageY - origPosY);

			if(destX < 0 && destX > (-($("#image").width() - $("#container").width())))
			{
				$("#image").css({marginLeft:destX+"px"});				
			}
			if(destY < 0 && destY > (-($("#image").height() - $("#container").height())))
			{
				$("#image").css({marginTop:destY+"px"});	
			}			
		}		
	}).mouseup(function(e){
		origPosX = null;
		origPosY = null;
		$("body").css({cursor:"default"});
	});

	$("#image").mousedown(function(e){
		e.preventDefault();
		origPosX = e.pageX;
		origPosY = e.pageY;
		imgX = $("#image").css("margin-left").replace(/px/, "");
		imgY = $("#image").css("margin-top").replace(/px/, "");
		$("body").css({cursor:"move"});
		$("#refreshOpener").val("false");
	});
	
	if($("#containerWidth").val() != "" && $("#containerHeight").val() != "")
	{
		destWidth = $("#containerWidth").val();
		destHeight = $("#containerHeight").val();	
		resize(destHeight, destWidth);		
	}	
	
});

function getMinPercentage(origWidth, origHeight)
{	
		if($("#container").width()/$("#container").height() > 1)
		{
			if($("#container").width()/$("#container").height() <= origWidth / origHeight)
			{
				percent = Math.ceil(($("#container").height() / origHeight) * 100);
				$("#slider").slider('option', 'min', percent);				
			}
			else
			{
				percent = Math.ceil(($("#container").width() / origWidth) * 100);
				$("#slider").slider('option', 'min', percent);				
			}
			
		}
		else if($("#container").width()/$("#container").height() < 1)
		{	
			if($("#container").width()/$("#container").height() <= origWidth / origHeight)
			{
				percent = Math.ceil(($("#container").height() / origHeight) * 100);
				$("#slider").slider('option', 'min', percent);				
			}
			else
			{
				percent = Math.ceil(($("#container").width() / origWidth) * 100);
				$("#slider").slider('option', 'min', percent);
			}
		}
		else if($("#container").width() == $("#container").height())
		{
			if(origWidth >= origHeight)
			{
				percent = Math.ceil(($("#container").height() / origHeight) * 100);
				$("#slider").slider('option', 'min', percent);
			}
			else
			{
				percent = Math.ceil(($("#container").width() / origWidth) * 100);
				$("#slider").slider('option', 'min', percent);
			}
		}

		if($("#image").width()-Math.abs($("#image").css("margin-left").replace(/px/, "")) < $("#container").width())
		{
			imgRatio = origHeight/origWidth;
			$("#amount").text(percent);
			
			$("#image").css({
				width: $("#container").width() + "px",
				height: ($("#container").width() * imgRatio) + "px",
				marginLeft: 0,
				marginTop: 0
			});

			$('#slider').slider('option', 'value', percent);				
		}
		else
		{
			$('#slider').slider('option', 'value', $('#slider').slider('option', 'value'));
		}
		
		if($("#image").height()-Math.abs($("#image").css("margin-top").replace(/px/, "")) < $("#container").height())
		{
			imgRatio = origWidth/origHeight;
			$("#amount").text(percent);
			
			$("#image").css({
				width: ($("#container").height() * imgRatio) + "px",
				height: $("#container").height() + "px",
				marginLeft: 0,
				marginTop: 0
			});

			$('#slider').slider('option', 'value', percent);				
		}
		else
		{
			$('#slider').slider('option', 'value', $('#slider').slider('option', 'value'));
		}				
}

function infoMessage(message)
{
	width = $('div#message').html(message).width();
	$('div#message').css("right", -width-10+"px").animate({"right": "0px"}, "normal", function(){
		setTimeout('$("div#message").animate({"right": -width-10+"px"}, "normal");', 2000);
	});
}